package models

import (
	awesomeTask "awesomeTask/commom"
	"awesomeTask/commom/parse"
	"awesomeTask/commom/timeHelper"
	"awesomeTask/system/log"
	"strings"
)

const TABLE_NAME = "t_datasourcetask_back_fill"
const sencond = 1

func NextTick(taskId float64) {
	data := awesomeTask.Query("select * from "+TABLE_NAME+" where id=?", taskId)
	if len(data) != 0 {
		taskConfig := data[0]
		taskConfig["run_time"] = parseNextTime(taskConfig["run_time"].(string), taskConfig["intervals"].(string))
		switch taskConfig["run_num"].(type) {
		case int64:
			taskConfig["run_num"] = taskConfig["run_num"].(int64) - 1
		}
		taskConfig["status"] = 1
		awesomeTask.Update(TABLE_NAME, taskConfig, "where id=?", taskConfig["id"])
	}
}
func parseNextTime(currentTime string, ticket string) string {
	timeStamp := timeHelper.TimeStringParseTimeStamp(currentTime)
	var nextTime string = ""
	var ticketRes int64 = 0
	var resultTimeStamp int64
	ticketParams := strings.Split(ticket, "*")
	switch ticketParams[1] {
	case "minute":
		ticketRes = sencond * 60
		break
	case "hour":
		ticketRes = sencond * 60 * 60
		break
	case "day":
		ticketRes = sencond * 60 * 60 * 24
	case "week":
		ticketRes = sencond * 60 * 60 * 24 * 7
	case "month":
		nextTime = timeHelper.NextMonths(currentTime, parseHelper.ParseInt(ticketParams[0]))
		break
	case "year":
		nextTime = timeHelper.NextYears(currentTime, parseHelper.ParseInt(ticketParams[0]))
		break
	default:
		err := "无法解析的时间间隔请检查您的配置"
		log.GetLogger().Error(err)
		panic(err)
	}
	if nextTime == "" && ticketRes == 0 {
		err := "无法解析的时间间隔请检查您的配置"
		log.GetLogger().Error(err)
		panic(err)
	}
	if nextTime != "" {
		resultTimeStamp = timeHelper.TimeStringParseTimeStamp(nextTime)
	}
	if ticketRes != 0 {
		resultTimeStamp = timeStamp + ticketRes*parseHelper.StringParseInt64(ticketParams[0])
	}
	if resultTimeStamp > timeHelper.NowInt() {
		return timeHelper.TimeStampParseString(resultTimeStamp)
	}
	return parseNextTime(timeHelper.TimeStampParseString(resultTimeStamp), ticket)
}
